<?php
namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\extenders\MenuManage;
use common\components\helpers\Fun;
use common\components\helpers\Tree;
use common\models\datas\Admissionfee;
use common\models\datas\CardAttr;
use common\models\datas\Cate;
use common\models\datas\Reservation;
use common\models\datas\Student;
use webfront\models\data\Customer;
use yii\db\Query;
use zhtfrontend\components\bases\BaseController;
use zhtfrontend\components\services\statistics\Statisticaldata;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\Arrangement;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassManageTeacher;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\Comment;
use zhtfrontend\models\datas\CommentInfo;
use zhtfrontend\models\datas\CommentRelation;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsAttr;
use zhtfrontend\models\datas\GoodsTeacher;
use zhtfrontend\models\datas\Orders;
use zhtfrontend\models\datas\OrdersItems;
use zhtfrontend\models\datas\Praise;
use zhtfrontend\models\datas\StudentCheck;
use Yii;
use zhtfrontend\models\datas\Teacher;
use zhtfrontend\models\forms\LoginForm;
use zhtfrontend\models\PasswordResetRequestForm;
use zhtfrontend\models\ResetPasswordForm;
use zhtfrontend\models\SignupForm;
use zhtfrontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\web\ViewAction;

/**
 * Site controller
 */
class SiteController extends BaseController
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['index', 'login', 'logout', 'error'],
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        //    die('系统正在升级.....');
        if(\Yii::$app->request->isAjax){
            \Yii::$app->response->format=Response::FORMAT_JSON;
            $ajax_object=new AjaxObject();
            if(\Yii::$app->request->post('menu_id')==null){
                throw new BadRequestHttpException(\Yii::t('zhtfrontend','信息不存在'),404);
            }
            $ajax_object->data=$this->menu[\Yii::$app->request->post('menu_id')];
            $ajax_object->content=(new MenuManage(MenuManage::LEFT_MENU,['id'=>(int)\Yii::$app->request->post('menu_id')]))->create();
            return $ajax_object;
        }
        $tabArr = [];
        $list = [];
        $new_students = 0;
        $appointment_count = 0;
        $order_count = 0;
        $favourable =  0;
        $type = '广场';
        $backlog = 0;
        $StatisticalItem = [];
        $site_id = Fun::getSiteId();
        $day_start = mktime(0, 0, 0, date("m", time()), date("d", time()), date("Y", time()));
        $day_end = mktime(23, 59, 59, date("m", time()), date("d", time()), date("Y", time()));
        $auth = \Yii::$app->authManager;
        $roles = $auth->getRolesByUser(\Yii::$app->user->id);
        if($roles != null) {
            foreach ($roles as $item) {
                switch ($item->name) {
                    case 'class_director':
                        $new_students += $new_students;
                        $appointment_count += $appointment_count;
                        $order_count += $order_count;
                        $favourable += $favourable;
                        $SettlementAuditCount = Statisticaldata::getAuditing(['status' => 10], 10);  //待审核结算数量
                        $SettlementAuditList = Statisticaldata::getAuditSettlementList(['status' => 10], 10,'classhouraccount/index');
                        $tabArr[] = ['title' => '待审核结算', 'id' => 1, 'count' => $SettlementAuditCount];
                        $list[] = ['id' => 1, 'list' => $SettlementAuditList];
                        $backlog += $SettlementAuditCount;
                        $classescount = Statisticaldata::getMechanicGoodsNum(['admin_id'=>\Yii::$app->user->id]); //约课数量
                        $studentCount = Statisticaldata::getMechanicGoodsNum(['admin_id'=>\Yii::$app->user->id],'customer_id'); //获取约课的学员数量
                        $StatisticalItem[] = [
                            'title'        => '机构好评率',
                            'statistics'  => 0,
                            'compare'     => 10,
                            'url'          => Fun::url(['positive/index']),
                            'id'          => 1
                        ];
                        $StatisticalItem[] = [
                            'title'        => '学员数量',
                            'statistics'  => $studentCount,
                            'compare'     => 10,
                            'url'         => 'javascript:;',
                            'id'          => 2
                         ];
                        $StatisticalItem[] = [
                            'title'        => '约课数量',
                            'statistics'  => $classescount,
                            'compare'     => 10,
                            'url'         => 'javascript:;',
                            'id'         => 3
                        ];
                        break;
                    case 'educational_administration':
                        $new_students = 0;
                        $appointment_count = 0;
                        $order_count = 0;
                        $favourable = 0;
                        $SubSettlementCount = Statisticaldata::getSubSettlementCount(); //待提报结算数量
                        $SubGoodsCount = Statisticaldata::getSubGoodsCount(['status' => 0, 'is_delete' => 0,'admin_id'=>\Yii::$app->user->id]);  //待提报上架数量
                        $SubGoodsList = Statisticaldata::getSubGoodsList(['status' => 0, 'is_delete' => 0,'admin_id'=>\Yii::$app->user->id], 'mechanicgoods/index');  //待提报上架列表
                        $AuditGoodsList = Statisticaldata::getSubGoodsList(['status' => 3, 'is_delete' => 0, 'admin_id' => \Yii::$app->user->id], 'squaregoods/index');  //待审核上架列表
                        $AuditGoodsCount = Statisticaldata::getAuditGoodsCount(['is_shelve' => 0, 'is_delete' => 0, 'admin_id' => \Yii::$app->user->id], 2);  //待审核上架数量
                        $SubSettlementList = Statisticaldata::getSubSettlementList(); //待提报结算
                        $tabArr[] = ['title' => '待提报上架', 'id' => 1, 'count' => $SubGoodsCount];
                        $tabArr[] = ['title' => '待审核上架', 'id' => 2, 'count' => $AuditGoodsCount];
                        $tabArr[] = ['title' => '待提报结算', 'id' => 3, 'count' => $SubSettlementCount];
                        $list[] = ['id' => 1, 'list' => $SubGoodsList];
                        $list[] = ['id' => 2, 'list' => $AuditGoodsList];
                        $list[] = ['id' => 3, 'list' => $SubSettlementList];
                        $backlog += ($SubSettlementCount+$SubGoodsCount+$AuditGoodsCount);
                        $classescount = Statisticaldata::getMechanicGoodsNum(); //约课数量
                        $studentCount = Statisticaldata::getMechanicGoodsNum([],'customer_id'); //获取约课的学员数量
                        $StatisticalItem[] = [
                            'title'        => '学员数量',
                            'statistics'  => $studentCount,
                            'compare'     => '9%↑',
                            'unit'         => '人',
                            'url'         => 'javascript:;',
                            'id'          => 2
                        ];
                        $StatisticalItem[] = [
                            'title'        => '约课次数',
                            'statistics'  => $classescount,
                            'compare'     => '9%↑',
                            'unit'         => '次',
                            'url'         => 'javascript:;',
                            'id'         => 3
                        ];
                        break;
                    case 'finance':
                        $new_students = 0;
                        $appointment_count = 0;
                        $order_count = 0;
                        $favourable = 0;
                        $SettlementSubCount = Statisticaldata::getAuditing(['status' => 12], 12);  //待审核结算数量
                        $SettlementCount = Statisticaldata::getAuditing(['status' => 13], 13);  //待结算数量
                        $AuditGoodsCount = Statisticaldata::getAuditGoodsCount(['is_shelve' => 0, 'is_delete' => 0], 4);  //待审核上架数量
                        $AuditGoodsList = Statisticaldata::getSubGoodsList(['is_shelve' => 0, 'is_delete' => 0], 'squaregoods/index');  //待审核上架列表
                        $SettlementSubList = Statisticaldata::getAuditSettlementList(['status' => 12], 12, 'classhouraccount/index');
                        $SettlementList = Statisticaldata::getSettlementList(['status' => 13], 13, 'classhouraccount/index');
                        $tabArr[] = ['title' => '待审核上架', 'id' => 1, 'count' => $AuditGoodsCount];
                        $tabArr[] = ['title' => '待审核结算', 'id' => 2, 'count' => $SettlementSubCount];
                        $tabArr[] = ['title' => '待结算', 'id' => 3, 'count' => $SettlementCount];
                        $list[] = ['id' => 1, 'list' => $AuditGoodsList];
                        $list[] = ['id' => 2, 'list' => $SettlementSubList];
                        $list[] = ['id' => 3, 'list' => $SettlementList];
                        $backlog += ($SettlementSubCount+$SettlementCount+$AuditGoodsCount);
                        break;
                    case 'mec_principal':
                        //取得当前登录机构id
                        $mechanicId = Fun::getMechanicIds();
                        //统计当天新增学员的数量
                        $teacherIds = Teacher::find()->select('id')->where(['mechanic_id' => $mechanicId])->column();
                        $commentIds = Comment::find()->select('id')->where(['object_type' => 1, 'object_id' => $teacherIds])->column();
                        $fraction = CommentRelation::find()->where(['comment_info_id' => [2, 3], 'comment_id' => $commentIds])->sum('for_value');

                        //机构好评率
                        $totalscore = 0;
                        $favourable = 0;
                        if (!empty($commentIds)) {
                            $count = count($commentIds);
                            $totalscore = $count * 5;
                            $favourable = round($fraction / $totalscore * 100);
                        }


                        //学生数量
                        $classIds = ClassManage::find()->select('class_id')->where(['mechanic_id' => $mechanicId, 'is_delete' => 0])->column();
                        $new_students = ClassStudent::find()->where(['class_manage_id' => $classIds, 'status' => [1, 2]])->groupBy('student_id')->count();

                        //预约次数

                        $appointment_count = OrdersItems::find()->joinWith('orderss')->where(['dmd_orders_items.mechanic_id' => $mechanicId])->count();
                        //统计当天卡激活数量
                        $order_count = '';

                        $SettlementSubCount = Statisticaldata::getMechanicAuditing(['status' => 11, 'mechanic_id' => \Yii::$app->user->identity->mechanic_id], 11);  //待审核结算数量
                        $AuditGoodsCount = Statisticaldata::getAuditGoodsCount(['is_shelve' => 0, 'is_delete' => 0, 'mechanic_id' => \Yii::$app->user->identity->mechanic_id], 1);  //待审核上架数量
                        $SettlementSubList = Statisticaldata::getAuditSettlementList(['status' => 11, 'mechanic_id' => \Yii::$app->user->identity->mechanic_id], 11, 'mechanichour/index');  //待审核结算列表
                        $AuditGoodsList = Statisticaldata::getSubGoodsList(['status' => 2, 'mechanic_id' => \Yii::$app->user->identity->mechanic_id], 'mechanicgoods/index');  //待审核结算列表
                        $tabArr[] = ['title' => '待审核上架', 'id' => 1, 'count' => $AuditGoodsCount];
                        $tabArr[] = ['title' => '待审核结算', 'id' => 2, 'count' => $SettlementSubCount];
                        $list[] = ['id' => 1, 'list' => $AuditGoodsList];
                        $list[] = ['id' => 2, 'list' => $SettlementSubList];
                        $backlog += ($SettlementSubCount+$AuditGoodsCount);
                        $classescount = Statisticaldata::getMechanicGoodsNum(['id'=>\Yii::$app->user->identity->mechanic_id]); //约课数量
                        $StatisticalItem[] = [
                            'title'        => '好评率',
                            'statistics'  => $favourable,
                            'compare'     => '9%↑',
                            'unit'         => '%',
                            'url'         => 'javascript:;',
                            'id'          => 1
                        ];
                        $StatisticalItem[] = [
                            'title'        => '约课数量',
                            'statistics'  => $classescount,
                            'compare'     => '9%↑',
                            'unit'         => '次',
                            'url'         => 'javascript:;',
                            'id'          => 3
                        ];
                        break;
                    case 'mechanic':
                        //取得当前登录机构id
                        $mechanicId = Fun::getMechanicIds();
                        //统计当天新增学员的数量
                        $teacherIds = Teacher::find()->select('id')->where(['mechanic_id' => $mechanicId])->column();
                        $commentIds = Comment::find()->select('id')->where(['object_type' => 1, 'object_id' => $teacherIds])->column();
                        $fraction = CommentRelation::find()->where(['comment_info_id' => [2, 3], 'comment_id' => $commentIds])->sum('for_value');

                        //机构好评率
                        $totalscore = 0;
                        $favourable = 0;
                        if (!empty($commentIds)) {
                            $count = count($commentIds);
                            $totalscore = $count * 5;
                            $favourable = round($fraction / $totalscore * 100);
                        }


                        //学生数量
                        $classIds = ClassManage::find()->select('class_id')->where(['mechanic_id' => $mechanicId, 'is_delete' => 0])->column();
                        $new_students = ClassStudent::find()->where(['class_manage_id' => $classIds, 'status' => [1, 2]])->groupBy('student_id')->count();

                        //预约次数

                        $appointment_count = OrdersItems::find()->joinWith('orderss')->where(['dmd_orders_items.mechanic_id' => $mechanicId])->count();
                        //统计当天卡激活数量
                        $order_count = '';

                        $type = '机构';
                        $SubGoodsCount = Statisticaldata::getSubGoodsCount(['status' => 0, 'is_delete' => 0, 'mechanic_id' => \Yii::$app->user->identity->mechanic_id]);  //待审核上架数量
                        $SubGoodsList = Statisticaldata::getSubGoodsList(['status' => 0, 'is_delete' => 0, 'mechanic_id' => \Yii::$app->user->identity->mechanic_id], 'mechanicgoods/index');  //待提报上架列表
                        $tabArr[] = ['title' => '待提报上架', 'id' => 1, 'count' => $SubGoodsCount];
                        $list[] = ['id' => 1, 'list' => $SubGoodsList];
                        $backlog += $SubGoodsCount;
                        $classescount = Statisticaldata::getMechanicGoodsNum(['id'=>\Yii::$app->user->identity->mechanic_id]); //约课数量
                        $StatisticalItem[] = [
                            'title'        => '好评率',
                            'statistics'  => $favourable,
                            'compare'     => '9%↑',
                            'unit'         => '%',
                            'url'         => 'javascript:;',
                            'id'          => 1
                        ];
                        $StatisticalItem[] = [
                            'title'        => '约课数量',
                            'statistics'  => $classescount,
                            'compare'     => '9%↑',
                            'unit'         => '次',
                            'url'         => 'javascript:;',
                            'id'          => 3
                        ];
                        break;
                    case 'class_teacher':
                        //班主任---------------？？？
                        $class_teacher_id = \Yii::$app->user->identity->id;

                        $teacher_ids = Teacher::find()->select('id')->where(['parent_id' => $class_teacher_id])->column();
                        $commentIds = Comment::find()->select('id')->where(['object_type' => 1, 'object_id' => $teacher_ids])->column();
                        $fraction = CommentRelation::find()->where(['comment_info_id' => [2, 3], 'comment_id' => $commentIds])->sum('for_value');

                        //老师评率
                        $favourable = 0;
                        if (!empty($commentIds)) {
                            $count = count($commentIds);
                            $totalscore = $count * 5;
                            $favourable = round($fraction / $totalscore * 100);
                        }
                        //统计当天新增学员的数量
                        $classIds = ClassManage::find()->select('class_id')->where(['headmaster' => $class_teacher_id])->column(Fun::getSiteDb());
                        $new_students = ClassStudent::find()->where(['class_manage_id' => $classIds, 'status' => [1, 2]])->groupBy('student_id')->count();

                        //统计当天的预约次数
                        $appointment_count = 0;

                        //卡激活数量
                        $order_count = 0;

                        //班主任好评
                        $tabArr = [];
                        break;
                    case 'marketing_director':
                        $AddCustomerCount = Statisticaldata::getRelationshipNum(['admin_id'=>\Yii::$app->user->id]);
                        $AssignCustomerCount = Statisticaldata::getRelationshipNum(['admin_id'=>\Yii::$app->user->id,'salesman_id'=>0]);
                        $StatisticalItem[] = [
                            'title'        => '添加用户',
                            'statistics'  => $AddCustomerCount,
                            'compare'     => '9%↑',
                            'unit'         => '人',
                            'url'         => 'javascript:;',
                            'id'          => 2
                        ];
                        $StatisticalItem[] = [
                            'title'        => '未指派',
                            'statistics'  => $AssignCustomerCount,
                            'compare'     => '9%↑',
                            'unit'         => '人',
                            'url'         => 'javascript:;',
                            'id'         => 6
                        ];
                        $StatisticalItem[] = [
                            'title'        => '已指派',
                            'statistics'  => $AddCustomerCount-$AssignCustomerCount,
                            'compare'     => '9%↓',
                            'unit'         => '人',
                            'url'         => 'javascript:;',
                            'id'         => 7
                        ];
                        break;
                    case 'marketing_commissioner':
                        $AddCustomerCount = Statisticaldata::getRelationshipNum(['admin_id'=>\Yii::$app->user->id]);
                        $AssignCustomerCount = Statisticaldata::getRelationshipNum(['admin_id'=>\Yii::$app->user->id,'salesman_id'=>0]);
                        $StatisticalItem[] = [
                            'title'        => '添加用户',
                            'statistics'  => $AddCustomerCount,
                            'compare'     => '9%↑',
                            'unit'         => '人',
                            'url'         => 'javascript:;',
                            'id'          => 2
                        ];
                        $StatisticalItem[] = [
                            'title'        => '未指派',
                            'statistics'  => $AssignCustomerCount,
                            'compare'     => '9%↑',
                            'unit'         => '人',
                            'url'         => 'javascript:;',
                            'id'         => 6
                        ];
                        $StatisticalItem[] = [
                            'title'        => '已指派',
                            'statistics'  => $AddCustomerCount-$AssignCustomerCount,
                            'compare'     => '9%↓',
                            'unit'         => '人',
                            'url'         => 'javascript:;',
                            'id'         => 7
                        ];
                        break;
                    case 'sales_director':
                        $StatisticalItem[] = [
                            'title'        => '负责用户',
                            'statistics'  => Statisticaldata::getRelationshipNum(['salesman_id'=>\Yii::$app->user->id]),
                            'compare'     => '9%↑',
                            'unit'         => '人',
                            'url'         => 'javascript:;',
                            'id'         => 2
                        ];
                        $StatisticalItem[] = [
                            'title'        => '转化',
                            'statistics'  => Statisticaldata::getRelationshipNum(['salesman_id'=>\Yii::$app->user->id,'is_customer'=>1]),
                            'compare'     => '9%↓',
                            'unit'         => '人',
                            'url'         => 'javascript:;',
                            'id'         => 6
                        ];
                        break;
                    case 'sales_specialist':
                        $StatisticalItem[] = [
                            'title'        => '负责用户',
                            'statistics'  => Statisticaldata::getRelationshipNum(['salesman_id'=>\Yii::$app->user->id]),
                            'compare'     => '9%↑',
                            'unit'         => '人',
                            'url'         => 'javascript:;',
                            'id'         => 2
                        ];
                        $StatisticalItem[] = [
                            'title'        => '转化',
                            'statistics'  => Statisticaldata::getRelationshipNum(['salesman_id'=>\Yii::$app->user->id,'is_customer'=>1]),
                            'compare'     => '9%↓',
                            'unit'         => '人',
                            'url'         => 'javascript:;',
                            'id'         => 6
                        ];
                        break;
                    default:
                        //系统管理员、超级管理员、广场高管、财务
                        //统计当天新增学员的数量
                        $teacherIds = Teacher::find()->select('id')->column();
                        $commentIds = Comment::find()->select('id')->where(['object_type' => 1, 'object_id' => $teacherIds])->column();
                        $fraction = CommentRelation::find()->where(['comment_info_id' => [2, 3], 'comment_id' => $commentIds])->sum('for_value');

                        //广场评率
                        $totalscore = 0;
                        $favourable = 0;
                        if (!empty($commentIds)) {
                            $count = count($commentIds);
                            $totalscore = $count * 5;
                            $favourable = round($fraction / $totalscore * 100);
                        }

                        $classIds = ClassManage::find()->select('class_id')->where(['is_delete' => 0])->column();
                        $new_students = ClassStudent::find()->where(['class_manage_id' => $classIds, 'status' => [1, 2]])->groupBy('student_id')->count();

                        //统计当天的预约次数
                        $appointment_count = OrdersItems::find()->joinWith('orderss')->where(['dmd_orders_items.teach_type' => 1])->count();
                        //统计当天卡激活数量
                        $card_count = CardAttr::find()->where(['status' => 1, 'site_id' => $site_id])->count();
                        $order_count = $card_count;
                        $StatisticalItem[] = [
                            'title'        => '广场好评率',
                            'statistics'  => 90,
                            'compare'     => '9%↑',
                            'unit'         => '%',
                            'url'         => 'javascript:;',
                            'id'          => 1
                        ];
                        $StatisticalItem[] = [
                            'title'        => '学员数量',
                            'statistics'  => $studentCount,
                            'compare'     => '9%↑',
                            'unit'         => '人',
                            'url'         => 'javascript:;',
                            'id'          => 2
                        ];
                        $StatisticalItem[] = [
                            'title'        => '约课次数',
                            'statistics'  => $classescount,
                            'compare'     => '9%↑',
                            'unit'         => '次',
                            'url'         => 'javascript:;',
                            'id'         => 3
                        ];
                        $StatisticalItem[] = [
                            'title'        => '卡激活率',
                            'statistics'  => 40,
                            'compare'     => '9%↓',
                            'unit'         => '次',
                            'url'         => 'javascript:;',
                            'id'         => 4
                        ];
                        break;
                }
            }
        }else{
            //系统管理员、超级管理员、广场高管、财务
            //统计当天新增学员的数量
            $teacherIds = Teacher::find()->select('id')->column();
            $commentIds = Comment::find()->select('id')->where(['object_type' => 1, 'object_id' => $teacherIds])->column();
            $fraction = CommentRelation::find()->where(['comment_info_id' => [2, 3], 'comment_id' => $commentIds])->sum('for_value');

            //广场评率
            $totalscore = 0;
            $favourable = 0;
            if (!empty($commentIds)) {
                $count = count($commentIds);
                $totalscore = $count * 5;
                $favourable = round($fraction / $totalscore * 100);
            }

            $classIds = ClassManage::find()->select('class_id')->where(['is_delete' => 0])->column();
            $new_students = ClassStudent::find()->where(['class_manage_id' => $classIds, 'status' => [1, 2]])->groupBy('student_id')->count();

            //统计当天的预约次数
            $appointment_count = OrdersItems::find()->joinWith('orderss')->where(['dmd_orders_items.teach_type' => 1])->count();
            //统计当天卡激活数量
            $card_count = CardAttr::find()->where(['status' => 1, 'site_id' => $site_id])->count();
            $order_count = $card_count;
            $classescount = Statisticaldata::getMechanicGoodsNum([]); //约课数量
            $studentCount = Statisticaldata::getMechanicGoodsNum([],'customer_id'); //获取约课的学员数量
            $StatisticalItem[] = [
                'title'        => '广场好评率',
                'statistics'  => 90,
                'compare'     => '9%↑',
                'unit'         => '%',
                'url'         => Fun::url(['positive/index']),
                'id'          => 1
            ];
            $StatisticalItem[] = [
                'title'        => '学员数量',
                'statistics'  => $studentCount,
                'compare'     => '9%↑',
                'unit'         => '人',
                'url'         => 'javascript:;',
                'id'          => 2
            ];
            $StatisticalItem[] = [
                'title'        => '约课次数',
                'statistics'  => $classescount,
                'compare'     => '9%↑',
                'unit'         => '次',
                'url'         => 'javascript:;',
                'id'         => 3
            ];
            $StatisticalItem[] = [
                'title'        => '卡激活率',
                'statistics'  => 40,
                'compare'     => '9%↓',
                'unit'         => '次',
                'url'         => 'javascript:;',
                'id'         => 4
            ];
        }
        $StatisticalItem[] = [
            'title'        => '待办事项',
            'statistics'  => $backlog,
            'compare'     => 10,
            'unit'         => '件',
            'url'         => 'javascript:;',
            'id'         => 5
        ];
        //转化率的统计
        //这个地方是获取所有月份的信息和当前月份一共有几条预约信息
        $orders_appoints=Fun::getSiteDb()->createCommand('SELECT FROM_UNIXTIME(created_at,"%Y%m") as months , COUNT(id) as count FROM {{%orders}} WHERE order_type = "appointment" GROUP BY months ')->queryAll();
        $orders_conversion=Fun::getSiteDb()->createCommand('SELECT FROM_UNIXTIME(created_at,"%Y%m") as months , COUNT(id) as count FROM {{%orders}} WHERE order_type = "conversion" GROUP BY months ')->queryAll();

        $orders_appoints_map = ArrayHelper::map($orders_appoints, 'months', 'count');
        $orders_conversion_map= ArrayHelper::map($orders_conversion, 'months', 'count');
        $conversions=[];
        $conversions_time=[];
        $conversions_value=[];
        //计算出表里面有的转化时间对应的转化比率
        foreach($orders_appoints_map as $key=>$val){
            if(isset($orders_appoints_map[$key])&&isset($orders_conversion_map[$key])&&$orders_appoints_map[$key]!==0){
                $conversions[$key]=$orders_conversion_map[$key]/$orders_appoints_map[$key]*100;
            }else{
                $conversions[$key]=0;
            }
        }
        //分别获取有的转化时间和转化比率(在前面的js中分别把数据填进去)
        foreach($conversions as $key=>$val){
            $conversions_time[]=$key;
            $conversions_value[]=$val;
        }
        //获取转化率的开始时间和结束时间
        $conversions_end=0;
        $conversions_start=0;
        foreach($conversions as $k=>$v){
            if($k>$conversions_end) {
                $conversions_end=$k;
            }
            if($conversions_start==0){
                $conversions_start=$k;
            }
        }
        $conversions_time_json=json_encode($conversions_time, JSON_UNESCAPED_UNICODE);
        $conversions_value_json=json_encode($conversions_value, JSON_UNESCAPED_UNICODE);

        //分成比例
        //续费率=续费/(正常+续费)
        return $this->render('index', ['conversions_end'=>$conversions_end,'conversions_start'=>$conversions_start,'conversions_time_json'=>$conversions_time_json,'conversions_value_json'=>$conversions_value_json,'new_students' => $new_students,'appointment_count'=>$appointment_count,'order_count'=>$order_count,'StatisticalItem'=>$StatisticalItem,'favourable'=>$favourable,'tabArr'=>$tabArr,'list'=>$list,'backlog'=>$backlog]);
    }

//下载apk
    function actionDownload(){
        header("Content-type:text/html;charset=utf-8");
        // $file_name="cookie.jpg";
        $file_name = "dmdpadapp.apk";
        //用以解决中文不能显示出来的问题
        $file_name = iconv("utf-8", "gb2312", $file_name);
        $file_sub_path = $_SERVER['DOCUMENT_ROOT']."/";
        $file_path = $file_sub_path.$file_name;
        //首先要判断给定的文件存在与否
        if (!file_exists($file_path))
        {
            echo "没有该文件";
            return;
        }

        $fp = fopen($file_path, "r");
        $file_size = filesize($file_path);
        //下载文件需要用到的头
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length:" . $file_size);
        Header("Content-Disposition: attachment; filename=" . $file_name);
        $buffer = 1024;
        $file_count = 0;
        //向浏览器返回数据
        while (!feof($fp) && $file_count < $file_size) {
            $file_con = fread($fp, $buffer);
            $file_count += $buffer;
            echo $file_con;
        }
        fclose($fp);
        exit;
    }
//    public function actionIndex()
//    {
////        if(\Yii::$app->request->isAjax){
////            \Yii::$app->response->format=Response::FORMAT_JSON;
////            $ajax_object=new AjaxObject();
////            if(\Yii::$app->request->post('menu_id')==null){
////                throw new BadRequestHttpException(\Yii::t('zhtfrontend','��Ϣ������'));
////            }
////            $ajax_object->data=$this->menu[\Yii::$app->request->post('menu_id')];
////            $ajax_object->content=(new MenuManage(MenuManage::LEFT_MENU,['id'=>(int)\Yii::$app->request->post('menu_id')]))->create();
////            return $ajax_object;
////        }
//
//        $day_start = mktime(0, 0, 0, date("m", time()), date("d", time()), date("Y", time()));
//        $day_end = mktime(23, 59, 59, date("m", time()), date("d", time()), date("Y", time()));
//        if (\Yii::$app->user->identity->role == 'mechanic') {
//            $mechanicId = Fun::getMechanicIds();
////            $orders_items_id = OrdersItems::find()->select('id')->where(['in', 'mechanic_id', $mechanicId])->andwhere(['>=', 'created_at', $day_start])->andwhere(['<=', 'created_at', $day_end])->column(Fun::getSiteDb());
////            $student = ClassStudent::find()->select('student_id')->where(['in', 'order_sales_id', $orders_items_id])->column(Fun::getSiteDb());
////            $new_students = count(array_unique($student));
//            $student = Fun::getSiteDb()->createCommand('SELECT student_id as student , COUNT(order_sales_id) as count FROM {{%student_check}} GROUP BY student ')->queryAll();
//            foreach ($student as $k => $v) {
//                if ($v['count'] !== '5') {
//                    unset($student[$k]);
//                }
//            }
//            $new_students = count($student);
//            $orders_id = OrdersItems::find()->select('orders_id')->where(['in', 'mechanic_id', $mechanicId])->andwhere(['>=', 'created_at', $day_start])->andwhere(['<=', 'created_at', $day_end])->column(Fun::getSiteDb());
//            $money = Orders::find()->select('remain_amount')->where(['in', 'id', $orders_id])->column(Fun::getSiteDb());
//            $order_money = '';
//            foreach ($money as $k => $v) {
//                $order_money += $v;
//            }
//            $appointment = Orders::find()->select('id')->where(['in', 'id', $orders_id])->andwhere(['order_type' => 'appointment'])->column(Fun::getSiteDb());
//            $appointment_count = count($appointment);
//            $order_count = count($money);
//
//            $type = '机构';
//            $common_id = Comment::find()->select('id')->where(['object_type' => 2])->andwhere(['in', 'object_id', $mechanicId])->column(Fun::getSiteDb());
//            $teacher_score_good = CommentRelation::find()->select('for_value')->where(['in', 'comment_id', $common_id])->andwhere(['>=', 'for_value', 4])->column(Fun::getSiteDb());
//            $teacher_score_all = CommentRelation::find()->select('for_value')->where(['in', 'comment_id', $common_id])->column(Fun::getSiteDb());
//            $good_count = !empty($teacher_score_good) ? count($teacher_score_good) : 0;
//            $all_count = !empty($teacher_score_all) ? count($teacher_score_all) : 1;
//            $favourable = floor(($good_count / $all_count) * 100);
//
//        } elseif (\Yii::$app->user->identity->role == 'admin' || \Yii::$app->user->identity->role == 'administrator' || \Yii::$app->user->identity->role == 'manager' || \Yii::$app->user->identity->role == 'finance') {
////            $orders_items_id = OrdersItems::find()->select('id')->where(['>=','created_at',$day_start])->andwhere(['<=','created_at',$day_end])->column(Fun::getSiteDb());
////            $student = ClassStudent::find()->select('student_id')->where(['in','order_sales_id',$orders_items_id])->column(Fun::getSiteDb());
////            $new_students = count(array_unique($student));
//            //$student_time=StudentCheck::find()->select('')->where(['>=','created_at',$day_start])->andwhere(['<=','created_at',$day_end])->column(Fun::getSiteDb());
//            $student = Fun::getSiteDb()->createCommand('SELECT student_id as student , COUNT(order_sales_id) as count FROM {{%student_check}} GROUP BY student ')->queryAll();
//            foreach ($student as $k => $v) {
//                if ($v['count'] !== '5') {
//                    unset($student[$k]);
//                }
//            }
//            $new_students = count($student);
//            $orders_id = OrdersItems::find()->select('orders_id')->where(['>=', 'created_at', $day_start])->andwhere(['<=', 'created_at', $day_end])->column(Fun::getSiteDb());
//            $money = Orders::find()->select('remain_amount')->where(['in', 'id', $orders_id])->column(Fun::getSiteDb());
//            $order_money = '';
//            foreach ($money as $k => $v) {
//                $order_money += $v;
//            }
//            $appointment = Orders::find()->select('id')->where(['in', 'id', $orders_id])->andwhere(['order_type' => 'appointment'])->column(Fun::getSiteDb());
//            $appointment_count = count($appointment);
//            $order_count = count($money);
//
//            $type = '广场';
//            $favourable = 100;
//        } elseif (\Yii::$app->user->identity->role == 'teache_teacher') {
//            $teacher_id = \Yii::$app->user->identity->teacher_id;
//            $goods_id = GoodsAttr::find()->select('goods_id')->where(['attribute_id' => $teacher_id, 'obj_type' => 'teacher'])->column(Fun::getSiteDb());
//            $orders_items_id = OrdersItems::find()->select('id')->where(['in', 'goods_id', $goods_id])->andwhere(['>=', 'created_at', $day_start])->andwhere(['<=', 'created_at', $day_end])->column(Fun::getSiteDb());
//            $student_id = StudentCheck::find()->select(['student_id'])->where(['in', 'order_sales_id', $orders_items_id])->column(Fun::getSiteDb());
////            $student = ClassStudent::find()->select('student_id')->where(['in', 'order_sales_id', $orders_items_id])->column(Fun::getSiteDb());
//            $student = Fun::getSiteDb()->createCommand('SELECT student_id as student , COUNT(order_sales_id) as count FROM {{%student_check}} GROUP BY student ')->queryAll();
//            foreach ($student as $k => $v) {
//                if (!in_array($v['student'], $student_id)) {
//                    unset($student[$k]);
//                }
//                if ($v['count'] !== '5') {
//                    unset($student[$k]);
//                }
//            }
//            $new_students = count($student);
//            $orders_id = OrdersItems::find()->select('orders_id')->where(['in', 'goods_id', $goods_id])->andwhere(['>=', 'created_at', $day_start])->andwhere(['<=', 'created_at', $day_end])->column(Fun::getSiteDb());
//            $money = Orders::find()->select('remain_amount')->where(['in', 'id', $orders_id])->column(Fun::getSiteDb());
//            $order_money = '';
//            foreach ($money as $v) {
//                $order_money += $v;
//            }
//            $appointment = Orders::find()->select('id')->where(['in', 'id', $orders_id])->andwhere(['order_type' => 'appointment'])->column(Fun::getSiteDb());
//            $appointment_count = count($appointment);
//            $order_count = count($money);
//
//            $type = '老师';
//            $common_id = Comment::find()->select('id')->where(['object_type' => 1, 'object_id' => $teacher_id])->column(Fun::getSiteDb());
//            $teacher_score_good = CommentInfo::find()->select('for_value')->where(['in', 'comment_id', $common_id])->andwhere(['>=', 'for_value', 4])->column(Fun::getSiteDb());
//            $teacher_score_all = CommentRelation::find()->select('for_value')->where(['in', 'comment_id', $common_id])->column(Fun::getSiteDb());
//            $good_count = !empty($teacher_score_good) ? count($teacher_score_good) : 0;
//            $all_count = !empty($teacher_score_all) ? count($teacher_score_all) : 1;
//            $favourable = floor(($good_count / $all_count) * 100);
//
//        } elseif (\Yii::$app->user->identity->role == 'class_teacher') {
//            $class_teacher_id = \Yii::$app->user->identity->id;
//            $class_id = ClassManage::find()->select('class_id')->where(['headmaster' => $class_teacher_id])->column(Fun::getSiteDb());
//            $student_id = ClassStudent::find()->select('student_id')->where(['in', 'class_manage_id', $class_id])->column(Fun::getSiteDb());
////            $student = Student::find()->select('id')->where(['in','id',$student_id])->andwhere(['>=','created_at',$day_start])->andwhere(['<=','created_at',$day_end])->column(Fun::getSiteDb());
//            $student = Fun::getSiteDb()->createCommand('SELECT student_id as student , COUNT(order_sales_id) as count FROM {{%student_check}} GROUP BY student ')->queryAll();//����ط���ͳ�Ƴ���ÿ��ѧ���ֱ����˶��ٴο�
//            foreach ($student as $k => $v) {
//                if (!in_array($v['student'], $student_id)) {
//                    unset($student[$k]);
//                }
//                if ($v['count'] !== '5') {
//                    unset($student[$k]);
//                }
//            }
//            $new_students = count($student);
//            $orders_items_ids = ClassStudent::find()->select('order_sales_id')->where(['class_manage_id' => $class_id])->column(Fun::getSiteDb());
//            $orders_items_id = array_unique($orders_items_ids);
//            $orders_id = OrdersItems::find()->select('orders_id')->where(['in', 'id', $orders_items_id])->andwhere(['>=', 'created_at', $day_start])->andwhere(['<=', 'created_at', $day_end])->column(Fun::getSiteDb());
//            $money = Orders::find()->select('remain_amount')->where(['in', 'id', $orders_id])->column(Fun::getSiteDb());
//            $order_money = '';
//            foreach ($money as $v) {
//                $order_money += $v;
//            }
//            $appointment_count = 0;
//            $order_count = 0;
//
//            $type = '班主任';
//            $favourable = 100;
//        } else {
//            $new_students = 0;
//            $order_money = 0;
//            $appointment_count = 0;
//            $order_count = 0;
//            $type = '广场';
//            $favourable = 100;
//        }
//        $orders_appoints = Fun::getSiteDb()->createCommand('SELECT FROM_UNIXTIME(created_at,"%Y%m") as months , COUNT(id) as count FROM {{%orders}} WHERE order_type = "appointment" GROUP BY months ')->queryAll();
//        $orders_conversion = Fun::getSiteDb()->createCommand('SELECT FROM_UNIXTIME(created_at,"%Y%m") as months , COUNT(id) as count FROM {{%orders}} WHERE order_type = "conversion" GROUP BY months ')->queryAll();
//
//        $orders_appoints_map = ArrayHelper::map($orders_appoints, 'months', 'count');
//        $orders_conversion_map = ArrayHelper::map($orders_conversion, 'months', 'count');
//        $conversions = [];
//        $conversions_time = [];
//        $conversions_value = [];
//        foreach ($orders_appoints_map as $key => $val) {
//            if (isset($orders_appoints_map[$key]) && isset($orders_conversion_map[$key]) && $orders_appoints_map[$key] !== 0) {
//                $conversions[$key] = $orders_conversion_map[$key] / $orders_appoints_map[$key] * 100;
//            } else {
//                $conversions[$key] = 0;
//            }
//        }
//        foreach ($conversions as $key => $val) {
//            $conversions_time[] = $key;
//            $conversions_value[] = $val;
//        }
//        $conversions_end = 0;
//        $conversions_start = 0;
//        foreach ($conversions as $k => $v) {
//            if ($k > $conversions_end) {
//                $conversions_end = $k;
//            }
//            if ($conversions_start == 0) {
//                $conversions_start = $k;
//            }
//        }
//        $conversions_time_json = json_encode($conversions_time, JSON_UNESCAPED_UNICODE);
//        $conversions_value_json = json_encode($conversions_value, JSON_UNESCAPED_UNICODE);
//
//        return $this->render('index', ['conversions_end' => $conversions_end, 'conversions_start' => $conversions_start,
//            'conversions_time_json' => $conversions_time_json, 'conversions_value_json' => $conversions_value_json, 'new_students' => $new_students,
//            'order_money' => $order_money, 'appointment_count' => $appointment_count, 'order_count' => $order_count, 'type' => $type, 'favourable' => $favourable]);
//    }


    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {

        $this->layout=false;
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        $site_data=Fun::cache('site_cache',false);
        $site_id=Fun::getSiteId();
        $imgs=['logo'=>'','background_img'=>''];
        foreach($site_data as $k=>$v){
            if($v['id']==$site_id){
                $imgs['logo']=$v['logo'];
                $imgs['background_img']=$v['background_img'];
            }
        }
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            if(\Yii::$app->user->identity->role === 'cashier'){
                $this->redirect(Fun::url(['customer/query']));
            }else{
                return $this->goBack();
            }
        } else {
            return $this->render('login', ['model' => $model,'imgs'=>$imgs]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();
        return $this->goHome();
    }

    //锁屏处理
    public function  actionLockscreen(){
        if(Yii::$app->request->isAjax){
            \Yii::$app->response->format = Response::FORMAT_JSON;
            \Yii::$app->session['lock_screen_username'] = \Yii::$app->user->identity->username;
            \Yii::$app->user->logout(false);
            $site_data=Fun::cache('site_cache',false);
            $site_id=Fun::getSiteId();
            $imgs=['logo'=>'','background_img'=>''];
            foreach($site_data as $k=>$v){
                if($v['id']==$site_id){
                    $imgs['logo']=$v['logo'];
                    $imgs['background_img']=$v['background_img'];
                }
            }
            return ['status'=>1,'logo'=>$imgs['logo'],'background_img'=>$imgs['background_img']];
        }else{
            return ['status'=>0];
        }

    }

    //锁屏登陆
    public function  actionLockscreenlogin(){
        if(\Yii::$app->request->isAjax){
            \Yii::$app->response->format = Response::FORMAT_JSON;
            if(isset(Yii::$app->session['lock_screen_username'])){
                $identity = Admin::find()->andWhere(['username'=>\Yii::$app->session['lock_screen_username']])->one();
                if($identity !==null){
                    $password = Yii::$app->security->validatePassword(Yii::$app->request->post('pass'), $identity->password);
                    if($password){
                        Yii::$app->user->login($identity);
                        unset(Yii::$app->session['lock_screen_username']);
                        return 1;
                    }else{
                        return -1;
                    }
                }else{
                    return -2;
                }
            } else {
                return 0;
            }
        }
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password was saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }

    //清除缓存
    public function actionNocache(){
        if(Yii::$app->request->isAjax){
            \Yii::$app->response->format = Response::FORMAT_JSON;
            \Yii::$app->cache->flush();
        }
        return '清除缓存成功！';
    }
}
